package com.kumarn.android.imagesave.full.manager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.text.format.DateFormat;

public class ImageManager {

	private static final Uri IMAGE_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

	public Uri addImageAsApplication(ContentResolver cr, Bitmap bitmap,String filename) {
		long dateTaken = System.currentTimeMillis();
		String name = filename + ".jpg";
		File path = (new DirectoryManager()).getImageDir();
		return addImageAsApplication(cr, name, dateTaken, path.getPath(), name, bitmap, null);
	}

	public static Uri addImageAsApplication(ContentResolver cr, String name, long dateTaken,
											String directory, String filename, Bitmap source, byte[] jpegData) {

		OutputStream outputStream = null;
		String filePath = directory + "/" + filename;
		try {
			File dir = new File(directory);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File file = new File(directory, filename);
			if (file.createNewFile()) {
				outputStream = new FileOutputStream(file);
				if (source != null) {
					source.compress(CompressFormat.JPEG, 100, outputStream);
				} else {
					outputStream.write(jpegData);
				}
			}

		} catch (FileNotFoundException ex) {
			return null;
		} catch (IOException ex) {
			return null;
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (Throwable t) {
				}
			}
		}

		ContentValues values = new ContentValues(7);
		values.put(Images.Media.TITLE, name);
		values.put(Images.Media.DISPLAY_NAME, filename);
		values.put(Images.Media.DATE_TAKEN, dateTaken);
		values.put(Images.Media.MIME_TYPE, "image/jpeg");
		values.put(Images.Media.DATA, filePath);
		return cr.insert(IMAGE_URI, values);
	}
}